﻿// @ts-ignore
import SparkMD5 from 'spark-md5';

/**
 * 计算文件MD5哈希值
 * @param {File} file - 文件对象
 * @returns {Promise<string>} MD5哈希值
 */
export const calculateFileMD5 = (file: File) => {
    return new Promise((resolve, reject) => {
        const chunkSize = 2 * 1024 * 1024; // 2MB每块
        const chunks = Math.ceil(file.size / chunkSize);

        let currentChunk = 0;

        const spark = new SparkMD5.ArrayBuffer();
        const fileReader = new FileReader();

        const loadNext = () => {
            const start = currentChunk * chunkSize;
            const end = Math.min(start + chunkSize, file.size);
            const chunk = file.slice(start, end);
            fileReader.readAsArrayBuffer(chunk);
        };

        fileReader.onload = e => {
            spark.append(e.target?.result);
            currentChunk++;

            if (currentChunk < chunks) {
                loadNext();
            } else {
                resolve(spark.end());
            }
        };

        fileReader.onerror = reject;
        loadNext();
    });
};
